package leetcode.code0028;

/**
 * KMP
 *
 * @author CaoYu
 * @date 2021年9月20日
 * @description
 */
public class Solution1 extends Solution28 {

	@Override
	public int strStr(String haystack, String needle) {
		char[] chars1 = haystack.toCharArray();
		char[] chars2 = needle.toCharArray();
		int len1 = chars1.length;
		int len2 = chars2.length;
		int[] p = new int[len2];
		// p中m位置记录数值n,表示[0,n-1]的字符串同[m-n+1,m]字符串相同
		for (int i = 1, j = 0; i < len2 && j < len2; i++) {
			while (j > 0 && chars2[i] != chars2[j]) {
				j = p[j - 1];
			}
			if (chars2[i] == chars2[j]) {
				j++;
			}
			p[i] = j;
		}
		for (int i = 0, j = 0; i < len1 && j < len2; i++) {
			while (j > 0 && chars1[i] != chars2[j]) {
				j = p[j - 1];
			}
			if (chars1[i] == chars2[j]) {
				j++;
			}
			if (j == len2) {
				return i - j + 1;//i-(j-1)
			}
		}
		return len2 == 0 ? 0 : -1;//当 needle 是空字符串时我们应当返回 0
	}

	public static void main(String[] args) {
		Solution1 so = new Solution1();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
